from docx import Document
from docx.shared import Pt

def split_docx(input_file, answers_file, questions_file):
    # 创建一个新的文档来存放答案
    answers_doc = Document()
    # 创建一个新的文档来存放试题
    questions_doc = Document()

    # 读取原始文档
    original_doc = Document(input_file)

    # 初始化计数器
    answer_counter = 1

    # 遍历原始文档中的所有段落
    for paragraph in original_doc.paragraphs:
        # 检查段落是否以"答案："开头
        if paragraph.text.startswith("答案："):
            # 在答案文档中添加带有编号的新段落
            new_paragraph = answers_doc.add_paragraph(f"{answer_counter}. {paragraph.text}")
            # 增加计数器
            answer_counter += 1
        else:
            # 将段落复制到试题文档
            questions_doc.add_paragraph(paragraph.text)

    # 保存答案文档
    answers_doc.save(answers_file)

    # 保存试题文档
    questions_doc.save(questions_file)

if __name__ == "__main__":
    input_file = "123.docx"
    answers_file = "答案.docx"
    questions_file = "试题.docx"

    split_docx(input_file, answers_file, questions_file)
    print("文件分割完成！")